package com.hua.nailcampus.auth;

import com.hua.nailcampus.acl.model.User;
import com.hua.nailcampus.utils.JwtHelper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author:chenjianhua
 * @Date:2023/11/22 10:10
 * @Version 1.8
 */
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {

    private RedisTemplate redisTemplate;

    public UserLoginInterceptor(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        this.getUserLoginVo(request);
        return true;
    }

    private void getUserLoginVo(HttpServletRequest request) {
        //从请求头中获取token
        String token = request.getHeader("token");
        //判断token不为空
        if (!StringUtils.isEmpty(token)) {
            //从token中获取userId
            Integer userId = JwtHelper.getUserId(token);
            //根据userId到Redis中获取用户信息
            User user = (User) redisTemplate.opsForValue()
                    .get("user:login:" + userId);
            //获取数据放到ThreadLocal中
            if(user != null){
                AuthContextHolder.setUserId(userId);
                AuthContextHolder.setUse(user);
            }
        }

    }

}
